var badLevel = 1;
var desc = '';
var needRepair = 0;
var repairFlag = 1;
var fileName = '';
var userId,taskId,siteId;
var siteClassDetailIds = [];
var checkResults = [];
mui.init({
	beforeback: function() {
	　　 //获得父页面的webview
		var list = plus.webview.currentWebview().opener();
	　　 //触发父页面的自定义事件(refresh),从而进行刷新
		mui.fire(list, 'refresh');
		//返回true,继续页面关闭逻辑
		return true;
	}
});

mui.plusReady(function() {
	self = plus.webview.currentWebview();
	siteId = self.info.siteId;
	planId = self.info.planId;

	//taskId = self.info.taskId;
	userId = localStorage.getItem("userId");
	document.querySelector('.mui-table-view.badLevel').addEventListener('selected',function(e){
		if(e.detail.el.innerText.trim() == '一级'){
			badLevel = 1;
		}else if (e.detail.el.innerText.trim() == '二级') {
			badLevel = 2;
		}else {
			badLevel = 3;
		}
	});
	console.log("siteId"+siteId)
	request("/app/alarm/scan/site/task/"+siteId+"/"+userId, "GET",{
	}, function(res) {
		console.log(JSON.stringify(res))
		if(res.code==0){
			render('#list_wrap', 'taskList', res);
			for(var i=0,len=res.result.length;i<len;i++){
				siteClassDetailIds.push(res.result[i].id)
			}
		}
		else{
			
		}
	}, true, function() {

	});
	request("/app/alarm/select/task/id/"+siteId+"/"+userId+"/"+planId, "GET",{
	}, function(res) {
		if(res.code==0){
			taskId = res.result;
		}
		else{
			
		}
	}, true, function() {

	});
	/*document.querySelector('.mui-table-view.need-repair-radio').addEventListener('selected',function(e){
		if(e.detail.el.innerText.trim() == '需要维修'){
			needRepair = 1;
			repairFlag = 2;
			document.getElementById('comple').classList.remove('mui-selected');
			document.getElementById('unComple').classList.add('mui-selected');
		}else if(e.detail.el.innerText.trim() == '不需要维修') {
			needRepair = 2;
			repairFlag = 1;
			document.getElementById('unComple').classList.remove('mui-selected');
			document.getElementById('comple').classList.add('mui-selected');
		}
	});*/
	
	document.querySelector('.mui-table-view.repair-radio').addEventListener('selected',function(e){
		if(e.detail.el.innerText.trim() == '完好'){
			repairFlag = 1;
			needRepair = 0;
			document.getElementById('needRepair').classList.remove('mui-selected');
			document.getElementById('noNeedRepair').classList.add('mui-selected');
		}else if (e.detail.el.innerText.trim() == '不完好') {
			repairFlag = 0;
			//needRepair = 1;
//			document.getElementById('noNeedRepair').classList.remove('mui-selected');
//			document.getElementById('needRepair').classList.add('mui-selected');
		}
	});
	
	document.getElementById('reportBtn').addEventListener('tap',function(){
		postTask(2)
	})
	document.getElementById('completeBtn').addEventListener('tap',function(){
		postTask(1)
	})

	// 弹出系统选择按钮框
	mui("body").on("tap","#selectImg",function(){
		page.imgUp();
	})
	
})

document.addEventListener("plusready", function() {
	plus.webview.currentWebview().opener().close("none");
});
//拍照、相册
var page={
	imgUp:function(){
		var m=this;
		plus.nativeUI.actionSheet({cancel:"取消",buttons:[
			{title:"拍照"},
			{title:"从相册中选择"}
		]}, function(e){//1 是拍照  2 从相册中选择
			switch(e.index){
				case 1:clickCamera();break;
				case 2:clickGallery();break;
			}
		});
	}
	//摄像头
}
	
function clickGallery() {
	plus.gallery.pick(function(path) {
		//console.log(path)
		plus.zip.compressImage({
			src: path,
			dst: "_doc/chat/gallery/" + path,
			quality: 20,
			overwrite: true
		}, function(e) {
			//console.log(JSON.stringify(e))
			var image = new Image();
			image.src = path;
			if(path){
			  image.onload =function (){
			  	var dataUrl = getBase64Image(image);
			  	//console.log(dataUrl)
			  	var file = dataURLtoFile(dataUrl, 'sanm'+ new Date().getTime());
			  	uploadImg(file);
			  }
			}

		}, function(err) {
			console.error("压缩失败：" + err.message);
		});

	}, function(err) {});
};
	
function clickCamera() {
	var cmr = plus.camera.getCamera();
	var res = cmr.supportedImageResolutions[0];
	var fmt = cmr.supportedImageFormats[0];
	cmr.captureImage(function(path) {
		//plus.io.resolveLocalFileSystemURL(path, function(entry) {
		plus.io.resolveLocalFileSystemURL(path, function(entry) {
			var localUrl = entry.toLocalURL();
			//console.log(localUrl)
			plus.zip.compressImage({
				src: localUrl,
				dst: "_doc/chat/camera/" + localUrl,
				quality: 20,
				overwrite: true
			}, function(e) {
				var image = new Image();
				image.src = e.target;
				if(e.target){
				  image.onload =function (){
				  	var dataUrl = getBase64Image(image);
				  	//console.log(dataUrl)
				  	var file = dataURLtoFile(dataUrl, 'sanm'+ new Date().getTime());
				  	uploadImg(file);
				  }
				}
			}, function(err) {
				console.log("压缩失败：  " + err.message);
			});
		});
	}, function(err) {
		console.error("拍照失败：" + err.message);
	}, {
		index: 1
	});
};

//传入图片路径，返回base64
function getBase64Image(img,width,height) {
	var canvas = document.createElement("canvas");
	canvas.width = width ? width : img.width;
	canvas.height = height ? height : img.height;
	var ctx = canvas.getContext("2d");
	ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
	var dataURL = canvas.toDataURL();
	return dataURL;
}
function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
}

var fileArr = [];
// 添加任务处理详情
function postTask(type){
	desc = document.getElementById('question').value;
	if(desc.trim() == ''){
		return mui.toast('请填写问题描述');
	}
	// if(fileName == ''){
	// 	return mui.toast('请上传问题图片');
	// }
	var liArr = document.getElementById('list_wrap').getElementsByTagName("li");
	for(var i=0,len=liArr.length;i<len;i++){
		//console.log(liArr[i]..getAttribute("data-type"))
		if(liArr[i].className.indexOf("mui-selected") != "-1"){
			checkResults.push(liArr[i].getAttribute("data-type"))
		}
	}
	//console.log(checkResults)
	request("/app/alarm/add/inspect/task/site/detail", "POST",{
		badDesc: desc,
		badLevel: badLevel,
		//fileName: fileName,
		fileNameStr: fileArr.join(","),
		needRepair: needRepair,
		taskId: taskId,
		flag: repairFlag,
		type: type,
		appoint: 0,
		inspectUserId: parseInt(userId),
		siteClassDetailIds: siteClassDetailIds.join(","),
		checkResults: checkResults.join(",")
	}, function(res) {
		checkResults = [];
		if(res.code==0){
			mui.toast('提交成功');
			setTimeout(function(){
				mui.back()
//				openNew("bbsDetails.html", {
//					inspectUnitId: planId
//				});
			}, 1000)
			//mui.back();
			//openNew("tour.html");
			//plus.webview.show("tour/tour.html");
		}
		else{
			mui.toast(res.desc)
		}
//		appPage.endPullRefresh();
//		render('#list_wrap', 'taskList', res)
	}, true, function() {
		checkResults = []
//		appPage.endPullRefresh();
	});
}

var fileObj = document.getElementById('fileArr');
var selectImg = document.getElementById('selectImg');
function uploadImg(obj){
	console.log(obj)
	plus.nativeUI.showWaiting();
	//创建FormData对象
    var data = new FormData();
    //为FormData对象添加数据
    //data.append('image', obj.files[0]);
    data.append('image', obj);
	//console.log(obj.files[0])
	mui.ajax({
		url: APP_DOMAIN + '/upload/image',
	    type: 'POST',
	    data: data,
	    cache: false,
	    contentType: false,
	    processData: false,
	    cache: false,
	    success: function(res){
	    	plus.nativeUI.closeWaiting();
	    	console.log(JSON.stringify(res));
	    	if(fileArr.length < 3){
		    	fileName = res;
		    	fileArr.push(res);
		    	var newImg = document.createElement('img');
		    	newImg.src = res;
		    	newImg.className = "new-img";
		    	fileObj.insertBefore(newImg, selectImg);
	    	}
	    	//document.getElementById('chooseImg').src = res;

	    },
	    error: function(err){
	    	plus.nativeUI.closeWaiting();
	    	mui.toast('图片上传失败')
	    	console.log(err)
	    }
	})
}

